package com.ra.system;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.espirit.eap.sa.Privilege;
import com.espirit.eap.sa.PrivilegeService;
import com.espirit.eap.sa.ScopeType;
import com.espirit.eap.sa.Template;
import com.espirit.eap.sa.UserTemplatePrivilege;
import com.googlecode.cswish.struts.spring.GenericService;

@Service
public class RaPrivilegeInitService {

	@Resource
	private PrivilegeService privilegeService;

	@Resource
	private GenericService genericService;

	/**
	 * 初始化所有权限数据：包括角色权限和所有模块下的子功能权限
	 */
	public void initAllPrivilege() {
		initFuncPrivilegeData();
		Map<String, Privilege> privilegeCache = initPrivilege();
		initRolePermission(privilegeCache);
	}

	public Map<String, Privilege> initPrivilege() {
		Map<String, Privilege> cache = new HashMap<>();
		// 模块级权限
		String category = null;
		checkAndAddPrivilege("房东模块-自己", "ra/landlord/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("分租模块-自己", "da/landlord/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("房东模块-楼房", "ra/landlord/building.",
				ScopeType.Global, category, cache);
		checkAndAddPrivilege("活动模块", "ra/activity/", ScopeType.Global,
				category, cache);
		checkAndAddPrivilege("微信模块", "ra/weixin/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("租客模块", "ra/rent/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("工具模块", "ra/util/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("财务模块", "da/finance/", ScopeType.Basic, category,
				cache);
		checkAndAddPrivilege("工作台模块", "da/workbench/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("租客预定模块", "ra/order/reserve/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("租客交租模块", "ra/order/rental/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("支付模块", "ra/pay/", ScopeType.Basic, category,
				cache);
		checkAndAddPrivilege("通用组件", "ra/component/mq/", ScopeType.Global,
				category, cache);

		checkAndAddPrivilege("工作日志模块", "ra/worklog/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("意见反馈模块", "ra/feedback/", ScopeType.Basic,
				category, cache);
		checkAndAddPrivilege("品牌公寓", "ra/brand/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("百万活动", "ra/coupon/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("便捷交租", "wr/rental/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("系统服务", "ra/system/", ScopeType.Global, category,
				cache);
		checkAndAddPrivilege("房源发布模块", "ra/wr/", ScopeType.Basic, category,
				cache);
		checkAndAddPrivilege("打印模块", "da/print/", ScopeType.Basic, category,
				cache);
		// 娱乐宝
		checkAndAddPrivilege("娱乐宝", "sscc/", ScopeType.Basic, category,
				cache);

		// 统计权限
//		category = "统计V2";
//		checkAndAddPrivilege("统计主页面v2", "fxcrm/statis/statis.view",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("统计房东注册数v2",
//				"fxcrm/statis/statistics.statisticNewUser", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("分类统计房东注册数v2",
//				"fxcrm/statis/statistics.statisticNewUserCategory",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("房东注册渠道统计v2", "/fxcrm/statis/userChannel.analyse",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege(
//				"楼房房东数统计v2",
//				"fxcrm/statis/buildingLandlordStatistics.analyseBuildingLandlord",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("房源数统计v2",
//				"fxcrm/statis/buildingLandlordStatistics.analyseRoom",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege(
//				"租客与微信用户数统计v2",
//				"fxcrm/statis/buildingLandlordStatistics.analyseTenantUserWeixinUser",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("微信用户来源统计v2",
//				"fxcrm/statis/weixinUserStatis.analyse", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("按地区（省/市）统计房东用户v2",
//				"fxcrm/statis/statistics.analyseUserByAdress",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("按地区（省/市）统计房源v2",
//				"fxcrm/statis/roomStatistics.analyseRoomByAdress",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("用户转化率统计v2",
//				"fxcrm/statis/userConversion.analyse", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("用户留存率统计v2", "fxcrm/statis/userRetention.analyse",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("系统访问模块统计v2", "fxcrm/statis/moduleAccess.analyse",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("房东访问模块统计v2",
//				"fxcrm/statis/moduleAccess.analyseApp", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("最近两天房东登录次数及排名统计v2",
//				"fxcrm/statis/loginStatistics.analyse", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("房东登录次数、总时长统计v2",
//				"fxcrm/statis/loginStatistics.analyseMoreLogin",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("便民服务推广统计v2",
//				"fxcrm/statis/serviceInfoStatistics.analyse", ScopeType.Global,
//				category, cache);
//		checkAndAddPrivilege("客服-房东统计v2",
//				"fxcrm/statis/statistics.analyseLandlordUser",
//				ScopeType.Global, category, cache);
//		checkAndAddPrivilege("性能分析v2", "fxcrm/statis/performanceLog.analyse",
//				ScopeType.Global, category, cache);

		return cache;
	}

	public void initRolePermission(Map<String, Privilege> cache) {
		// 2. add permission template
		bindTemplatePrivilege(cache, "anonymity.free",
				//"espirit/eap/manager/dictionary.search", "ra/landlord/landlordUser.searchDictionaryList",
				//"index", "index.execute",
//				"ra/rent/roomRetrieval.searchRoom", 
//				"ra/rent/roomRetrieval.viewRoomDetail", "ra/rent/roomRetrieval.viewDetail", 
//				"ra/rent/loginAndRegister._login", "ra/rent/roomRetrieval._register",
//				"ra/rent/roomRetrieval._forgetPassword", "ra/rent/roomRetrieval._setPassword",
//				"ra/rent/roomRetrieval.retrievePassword", "ra/rent/roomRetrieval.register",
//				"ra/weixin/roomInfo.searchRoomInfo",
//				"ra/weixin/roomInfo.viewRoomInfo", "ra/weixin/o2o/serviceInfo.getAllServiceInfo",
//				"ra/weixin/o2o/serviceInfo.getServiceInfo", "ra/weixin/o2o/serviceInfo.view",
//				"ra/wap/wap.searchRoomInfoByBuildingId",
//				"ra/rent/roomRetrieval.searchMapRoom", "ra/rent/roomRetrieval._register", 
//				"ra/rent/roomRetrieval.viewFile", "ra/weixin/weixinUser.bindingWeixinUser",
//				"index.city", "index.about", "ra/weixin/o2o/serviceInfo.hhzDownload", 
//				"ra/brand/brandApartment", "ra/brand/brandApartment.viewFile", "index.rentCouponPage", "index.rule", "index.appDownload",
				"sscc/activitySeller.searchSellers","sscc/activitySeller.searchBar","sscc/activitySeller.searchKTV",
				"ra/coupon/userCoupon.addUserCoupon", "ra/wap/wap._register", "ra/wap/wap._login", "ra/wap/wap.weixinBinding", 
				"ra/wap/wap.reg","sscc/coupon.addRegCoupon","sscc/activity.viewFile"
				
				);
		bindTemplatePrivilege(cache, "LandlordUserRole", "房东模块-自己", "分租模块-自己", "活动模块", "微信模块", "租客模块", "工具模块", "财务模块", "工作台模块", "租客预定模块", "租客交租模块", "通用组件", "工作日志模块", "意见反馈模块","品牌公寓","百万活动", "系统服务", "房源发布模块", "打印模块","娱乐宝");
		bindTemplatePrivilege(cache, "TenantUserRole", "活动模块", "微信模块", "租客模块", "工具模块", "租客预定模块", "租客交租模块", "支付模块","通用组件","品牌公寓","百万活动", "系统服务","便捷交租","娱乐宝");
		privilegeService.resetPrivilege();
	}

	/**
	 * 初始化所有的功能权限
	 */
	public void initFuncPrivilegeData() {
		String modelSimpleName;
		String method;
		String name = "TODO_Name";
		ScopeType scope = ScopeType.Basic;
		String[] privArray = getFuncPrivilegeArray();
		for (String srcPriv : privArray) {
			int splitIndex = srcPriv.lastIndexOf(".");
			modelSimpleName = srcPriv.substring(0, splitIndex);
			method = srcPriv.substring(splitIndex + 1, srcPriv.length());

			Privilege privilege = new Privilege();
			privilege.setModelSimpleName(modelSimpleName);
			privilege.setMethod(method);
			Privilege dbPrivilege = (Privilege) genericService.searchAll(
					privilege).getData(0);
			if (dbPrivilege != null) {
				privilege = dbPrivilege;
			}
			privilege.setName(name);
			privilege.setScopeType(scope);

			genericService.merge(privilege);
		}
	}

	private String[] getFuncPrivilegeArray() {
		String[] privArray = {
				"ra.landlord.workLog.ALL",				//RA module begin
				"ra.landlord.landlordUser.getLandlordUser",
				"ra.landlord.building.search",          
				"ra.landlord.building.add",
				"ra.landlord.building.print",
				"ra.landlord.building.update",
				"ra.landlord.building._update",
				"ra.landlord.building.delete",
				
				"ra.landlord.roomItemCfg.search",
				"ra.landlord.room.add",
				"ra.landlord.room.update",
				"ra.landlord.room._update",
				"ra.landlord.room._unRent",

				"ra.landlord.room.delete",
				"ra.landlord.room.search",
				"ra.landlord.room._search",
				"ra.landlord.room.throwLease",   
				"ra.landlord.room.undoThrowLease",
				
				"ra.landlord.roomRent._update",

				"ra.landlord.shareUnit.search",
				"ra.landlord.shareUnit.add",
				"ra.landlord.shareUnit.update",
				"ra.landlord.shareUnit.delete",
				
				"ra.landlord.share_unit._update",
				"ra.landlord.share_unit.search",
				
				"ra.landlord.feeRuleCfgDesc.search",
				"ra.landlord.feeRuleCfgDesc.add",
				"ra.landlord.feeRuleCfgDesc.update",
				"ra.landlord.feeRuleCfgDesc._update",
				"ra.landlord.feeRuleCfgDesc.delete",
				
				"ra.landlord.feeRuleCfg.search",
				"ra.landlord.feeRuleCfg.add",
				"ra.landlord.feeRuleCfg.delete",
				
				"ra.landlord.meter.search",
				"ra.landlord.meter.add",
				"ra.landlord.meter.update",
				"ra.landlord.meter.delete",
				
				"ra.landlord.room.searchMeter",
				
				"ra.landlord.agreement.add",
				"ra.landlord.agreement.update",
				
				"ra.landlord.tenantUser.search",
				"ra.landlord.tenantUser.update",
				
				"ra.landlord.fee.search",
				"ra.landlord.fee.add",
				"ra.landlord.fee.delete",
				"ra.landlord.fee.update",
				"ra.landlord.fee.print",
				"ra.landlord.fee.calculate",
				
				"ra.rent.roominfo.search",
				"ra.rent.roomInfo.update",			
				
				"ra.weixin.o2o.serviceInfo.add",
				"ra.weixin.o2o.serviceInfo.update",
				"ra.weixin.o2o.serviceInfo.delete",
				"ra.weixin.o2o.serviceInfo.search",
				"ra.weixin.o2o.serviceType.search",
				
				"ra.rent.roomInfo._searchPublishRoom",
				"ra.wr.roomPublish._searchPublishRoom",
				"ra.wr.roomPublish.search",
				
				"ra.landlord.landlordUser._resetPassword",
				"ra.landlord.landlordUser.resetPasswordAuth",
				"ra.landlord.landlordUser.resetPwd",
				
				"da.landlord.frame.index",					//DA module begin
				"da.workbench.welcome.index",
				
				/*"da.finance.daFinanceCategory.search",
				"da.finance.daFinanceCategory.add",   
				"da.finance.daFinanceCategory.update",   
				"da.finance.daFinanceCategory.delete", 
				
				"da.finance.daFinanceStatement.search",
				"da.finance.daFinanceStatement.add",
				"da.finance.daFinanceStatement.delete",
				"da.finance.daFinanceStatement.update",
				
				"da.finance.financeStatistics.analyse",
				"da.finance.financeStatistics.search",*/
				
				"da.landlord.daFeeRule.delete",
				
				"da.landlord.daChargeBill.print",
				"da.landlord.daChargeBill.search",
				"da.landlord.daChargeBill.createChargeBill",
				
				"da.landlord.daChargeItem.search",
				"da.landlord.daChargeItem.add",
				"da.landlord.daChargeItem.update",
				
				"da.landlord.daMeter.search",
				"da.landlord.daMeter.delete",
				"da.landlord.daMeter.update",
				"da.landlord.daMeter.add",

				"da.landlord.daOwner.search",
				"da.landlord.daOwner.add",
				"da.landlord.daOwner.delete",
				"da.landlord.daOwner.update",
				
				"da.landlord.daSuite.search",
				"da.landlord.daSuite.delete",
				"da.landlord.daSuite.update",
				"da.landlord.daSuite.add",
				"da.landlord.daSuite.rentRoom", 
				"da.landlord.daSuite.unRent" ,   //DA module 

				// 4.0版本
				
				//多处使用的URL：
				"da.print.batchPrint.searchDaRoom",
				"ra.landlord.building.searchBuilding",
				"da.landlord.daSuite.easyRuleCfg",

				// 分散式房源管理
				"da.landlord.daSuite.searchRoom",
				"da.landlord.roomSource._add",
				"ra.landlord.feeRuleCfg.searchMeterFeeRule",
				"da.landlord.room._search",
				"da.landlord.daSuite.addSuite",
				"ra.landlord.room.deleteRoom",
				"da.landlord.daRoom._updateBookAgreement",
				

				// 分散式未分类
				"da.landlord.daRoom._unRent",
				"da.landlord.daRoom.unRent",
				"da.landlord.daMeter.showMeterFeeRuleCfgForSuite",
				"da.landlord.daRoomMeterItem.searchMetersForSuite",
				"da.landlord.daMeter.analyse",

				// 集中式未分类
				"ra.landlord.meter.searchMeterByRoom",

				// 楼栋管理
				"ra.landlord.building.updateBuilding",
				"ra.util.addressCode.searchCode", // 地址
				"da.landlord.roomSource.updateRooms",
				"da.landlord.roomSource.update",
				"ra.landlord.room.addRoom",
				"da.landlord.roomSource.deleteRooms",
				"da.landlord.roomSource.copyBuildingFloor",
				"da.landlord.roomSource._updateRooms",
				"da.landlord.roomSource._batchAdd",
				"da.landlord.roomSource.batchAddRooms",
				"ra.landlord.room.searchRoomsInList",
				"ra.landlord.buildingFloor.searchBuildingFloor",
				"ra.landlord.room.searchRoom",
				"da.landlord.roomSource.add",

				// 房间管理
				"da.landlord.room._search",
				"ra.landlord.room.updateRoom",
				"ra.landlord.room.searchRoomsInGraphic",

				// 出租
				"ra.landlord.room._rent",
				"ra.landlord.room.rent",
				"da.landlord.daRoom._rent",
				"da.landlord.daRoom.rent",
				"da.landlord.daRoom._updateAgreement",
				"da.landlord.daRoom.updateAgreement",
				"ra.landlord.agreement._update",
				"ra.landlord.agreement.updateNew",

				// 收租
				"da.landlord.daRoom._collectRental",
				"da.landlord.daRoom.collectRental",
				"ra.landlord.room._collectRental",
				"ra.landlord.room.collectRental",
				"da.landlord.daConfirmMoney.confirmMoneyFromCollectForRa",
				"da.landlord.daConfirmMoney.confirmMoneyFromCollectForDa",

				// 费用
				"ra.landlord.fee._searchRoomHasPaidFee",
				"ra.landlord.fee.deleteFee",
				"da.print.batchPrint.printOneDaFee",

				// 预定
				"da.landlord.daRoom._book",
				"da.landlord.daRoom.book",
				"ra.landlord.room._book",
				"ra.landlord.room.book",

				// 集中式批量抄表
				"ra.landlord.meter.allSearch",
				"ra.landlord.meter.searchMeterCategory",
				"ra.landlord.shareUnit.searchWithMeter",
				"ra.landlord.meter.addMetersNew",
				"ra.landlord.meter.searchMeterByFeeRule",
				"ra.landlord.meter.deleteMeterNew",

				// 分散式批量抄表
				"da.landlord.daMeter.showMeterFeeRuleCfg",
				"da.landlord.daMeter.getSuiteMeters",
				"da.landlord.daMeter.deleteMeter",
				"da.landlord.daMeter.addMeters",
				"da.landlord.daRoomMeterItem.searchSuiteWithMeter",
				
				// 新增房源
				"da.landlord.daSuite._update",

				// 网上收租单
				"da.landlord.daConfirmMoney.view",
				"da.landlord.daConfirmMoney.searchRooms",
				"da.landlord.daConfirmMoney.confirmMoneyForDa",
				"da.landlord.daConfirmMoney.searchWithFee",
				"da.landlord.daConfirmMoney.confirmMoneyForRa",

				// 业主合约
				"da.landlord.daOwner._update",
				"da.landlord.daOwner.addDaOwner",
				"da.landlord.daOwner.stopAgreement",
				"da.landlord.daOwner._pay",
				"da.landlord.daOwner.pay",

				// 批量打印
				"da.print.room._search",
				"da.print.batchPrint.printRaFee",
				"da.print.batchPrint.searchRaRoom",
				"da.print.batchPrint.printDaFee",
				
				// 品牌公寓
				"ra.brand.brandApartment.apply",
				"ra.brand.brandApartment.brandApartmentSubmit",

				// 发布推广
				"ra.rent.roomInfo.updateSingleRoomPubInfo",
				"ra.wr.roomPublish.searchAllPublishRoomInfo",

				// 打印二维码
				"da.landlord.download.view",
				"da.landlord.download.downloadCodeImg",
				

				// 收费项设置
				"ra.landlord.feeRuleCfgDesc.searchAllFeeDesc",
				"ra.landlord.feeRuleCfgDesc.addDescAndFeeRuleCfg",
				"ra.landlord.feeRuleCfgDesc.updateDescAndSingleFeeRuleCfg",
				"da.andlord.daFeeRule.deleteFeeRuleDescCfg",
				"da.andlord.daFeeRule.update",
				"ra.landlord.feeRuleCfg.searchFeeRuleCfg",
				"da.andlord.daFeeRule.search",
				"ra.landlord.feeRule.search",
				"ra.landlord.feeRule.update",
				"ra.landlord.feeAddition.search",
				"ra.landlord.feeAddition.update",
				"ra.landlord.feeAdditionRecord.search",
				"ra.landlord.feeAdditionRecord.update",

				// 分摊设置
				"ra.landlord.room.searchWithRental",
				"ra.landlord.feeRuleCfg.searchFeeRule",
				"ra.landlord.shareUnit.addShareUnit",
				"ra.landlord.shareUnit.deleteShareUnit",
				"ra.landlord.shareUnit.searchShareUnit",
				"ra.landlord.shareUnit.updateShareUnit",
				// 财务汇总
				"da.finance.financeStatistics.analyse",

				// 财务流水
				"da.finance.daFinanceStatement.search",
				"da.finance.daFinanceStatement._update",
				"da.finance.daFinanceStatement.update",
				"da.finance.daFinanceStatement.add",
				"da.finance.daFinanceStatement.delete",
				"da.finance.daFinanceStatement.getAllRoom",// 房间名称
				"da.finance.daFinanceStatement.getAllTransaction",
				"dafinance.daFinanceStatement.getAllTradeCategory",
				"da.landlord.daRoom.search",
				"ra.landlord.simpleRoom.search",

				// 财务类别
				"da.finance.daFinanceCategory.search",
				"ra.landlord.feeRuleCfgDesc.get",
				"da.finance.daFinanceCategory.add",
				"da.finance.daFinanceCategory.update",
				"da.finance.daFinanceCategory.delete",

				// 工作日志
				"ra.landlord.workLog.search",
				"ra.landlord.workLog.addWorkLog",
				"ra.landlord.workLog.updateWorkLog",
				"ra.landlord.workLog.deleteWorkLog",

				// 便民信息
				"ra.weixin.o2o.serviceInfo.addServiceInfo",
				"ra.weixin.o2o.serviceInfo.updateServiceInfo",
				"ra.weixin.o2o.serviceInfo.deleteServiceInfo",
				"ra.weixin.o2o.serviceType.getAllServiceType",
				"ra.weixin.o2o.serviceInfo.getOptionalZones",
				
				//短信催缴
				"ra.weixin.personality.feeNotification.add",
				"ra.weixin.personality.reminderLetter.sendReminderLetterByRealTimeDaAndRa",
				"ra.weixin.personality.reminderLetter.getMessageCountByLandlordUser",
				"ra.weixin.personality.reminderLetter.getSendUsers",
				"ra.landlord.building.getBuildRooms"
		};
		return privArray;
	}

	private void bindTemplatePrivilege(Map<String, Privilege> cache,
			String templateName, String... privilegeNames) {
		Template template = new Template();
		template.setName(templateName);
		Template dbTemplate = genericService.searchAll(template).getData(0);
		if (dbTemplate != null) {
			template = dbTemplate;
		}

		List<UserTemplatePrivilege> privileges = template
				.getUserTemplatePrivileges();
		if (privileges == null) {
			privileges = new ArrayList<UserTemplatePrivilege>();
			template.setUserTemplatePrivileges(privileges);
		} else {
			privileges.clear();
		}

		for (String privilegeName : privilegeNames) {
			Privilege privilege = cache == null ? null : cache
					.get(privilegeName);
			if (privilege == null) {
				privilege = checkAndAddPrivilege(privilegeName, false,
						privilegeName, ScopeType.Global, cache);
			}

			UserTemplatePrivilege userTemplatePrivilege = new UserTemplatePrivilege();
			userTemplatePrivilege.setPrivilege(privilege);
			userTemplatePrivilege.setUserTemplate(template);
			privileges.add(userTemplatePrivilege);
		}
		genericService.merge(template);

	}

	private Privilege checkAndAddPrivilege(String name, String pathNoExtension,
			ScopeType scope, String subCategory, Map<String, Privilege> cache) {
		return checkAndAddPrivilege(name, true, pathNoExtension, scope, cache);
	}

	private Privilege checkAndAddPrivilege(String name, boolean nameAsI18n,
			String pathNoExtension, ScopeType scope,
			Map<String, Privilege> cache) {
		int methodIndex = pathNoExtension.lastIndexOf('.');
		String modelSimpleName;
		String method;
		if (methodIndex == -1) {
			modelSimpleName = pathNoExtension.replace('/', '.');
			method = Privilege.METHOD_ALL;
		} else {
			modelSimpleName = pathNoExtension.substring(0, methodIndex)
					.replace('/', '.');
			method = pathNoExtension.substring(methodIndex + 1);
		}

		Privilege privilege = new Privilege();
		privilege.setModelSimpleName(modelSimpleName);
		privilege.setMethod(method);

		Privilege dbPrivilege = genericService.searchAll(privilege).getData(0);
		if (dbPrivilege != null) {
			privilege = dbPrivilege;
		}
		privilege.setName(name);
		privilege.setScopeType(scope);
		if (nameAsI18n) {
			privilege.setI18n(name);
		}
		privilege = genericService.merge(privilege);

		cache.put(name, privilege);
		return dbPrivilege;
	}
}
